#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年2月22日

@author: Administrator
'''
from account import settings
from account.models import Profile
from common.decorators import unlogin_required
from common.utils import tool
from django.contrib import auth
from django.contrib.auth.models import User
from django.db.models.query_utils import Q
from django.http.response import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
import copy
import ujson as json


@csrf_exempt
@unlogin_required
def login(request):
    rsp_data = copy.copy(settings.ERROR['SUCC'])
    # 确定是否跳转过来的错误
    if request.method == 'GET' and request.GET.get('code', '10000'):
        for err in settings.ERROR.values():
            if request.GET.get('code', '10000') == err['code']:
                rsp_data = copy.copy(err)
                break

    user = None  # 创建user对象，并登录
    if request.method == 'POST':
        if request.POST.get('email', '') and request.POST.get('password', ''):
            email = request.POST['email']
            password = request.POST['password']
            user = auth.authenticate(username=email, password=password)
            if user:
                auth.login(request, user)
            else:
                rsp_data = copy.copy(settings.ERROR['AUTH_ERR'])
        else:
            rsp_data = copy.copy(settings.ERROR['PARA_ERR'])
    # 写入返回结果
    rsp_data['data'] = {}
    rsp_data['data']['next'] = request.REQUEST.get('next', settings.LOGIN_SUCESS_URL)
    if user:
        rsp_data['data']['name'] = user.first_name

    response = None
    if request.is_ajax():
        response = HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    else:
        if user:
            # 登录成功，跳转
            response = HttpResponseRedirect(rsp_data['data']['next'])
        else:
            # render登录页面
            response = render_to_response('account/admin/login.html', rsp_data)
    
    return response

@csrf_exempt
def loginout(request):
    '''
    function: 退出登录
    '''
    auth.logout(request)
    next = request.REQUEST.get('next', settings.LOGIN_URL)
    if request.is_ajax():
        response = HttpResponse(json.dumps(settings.ERROR['SUCC']), mimetype='application/json')
    else:
        response = HttpResponseRedirect(next)
    response.delete_cookie('userinfo', domain=settings.SESSION_COOKIE_DOMAIN)
    return response

def check_username(request):
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    username = request.POST["username"]
    user_id = request.POST.get("user_id", 0)
    
    if tool.is_email(username):
        if User.objects.filter(Q(username=username) | Q(email=username)).exclude(id=user_id).exists():
            rsp_data = copy.copy(settings.ERROR["EXIST_ERR"])
            rsp_data["msg"] = u"用户已存在"
            return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    elif tool.is_mobile(username):
        if User.objects.filter(username=username).exclude(id=user_id).exists() or Profile.objects.filter(mobile=username).exclude(user_id=user_id).exists():
            rsp_data = copy.copy(settings.ERROR["EXIST_ERR"])
            rsp_data["msg"] = u"用户已存在"
            return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    else:
        rsp_data = copy.copy(settings.ERROR["PARA_ERR"])
        rsp_data["msg"] = u"用户名格式错误"
        return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    
    
    
    
